from asset.models import *
from app.models import *
from django.db.models import Q
from rest_framework import status, serializers
# from rest_framework.exceptions import ValidationError

from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from rest_framework.decorators import action


from utils.custom_log   import log_start
logger = log_start('Serializers Mixin')

class AssetMixin:
    '''
    通用类mixin功能函数，执行通用操作
    '''
    def get_ssh_id(self, required=False):
        """
        根据id或者name 返回一个ssh_id实例对象
        """
        ssh_id = self.initial_data.get("ssh_id")
        logger.info('ssh_id')
        if ssh_id:
            logger.debug(f'get_ssh_id type:{type(ssh_id)} \n{ssh_id}')
            if isinstance(ssh_id,dict):
                if ssh_id['id']:
                    result = SSH_account.objects.get(pk=ssh_id['id'])
                else:
                    result = None
            elif isinstance(ssh_id,int):
                result = SSH_account.objects.get(pk=ssh_id)
            else:
                result = SSH_account.objects.get(name__icontains=ssh_id) 
        else:
            if required:
                raise serializers.ValidationError({'sshkey_id': '需要秘钥 ID !!!'})
            else:
                result = None
        return result
    
    def get_region_id(self, required=False):
        region_id = self.initial_data.get("region_id")
        if region_id:
            logger.debug(f'get_region_id type:{type(region_id)}')
            if isinstance(region_id,dict):
                if region_id['id']:
                    result = Region.objects.get(pk=region_id['id'])
                else:
                    result = None
            elif isinstance(region_id,int):
                result = Region.objects.get(pk=int(region_id))
            else:
                result = Region.objects.get(region__icontains=region_id) 
        else:
            if required:
                raise serializers.ValidationError({'region_id': '需要region ID'})
            else:
                result = None
        return result

    def get_platform_id(self, required=False):
        platform_id = self.initial_data.get("platform_id")
        if platform_id:
            logger.debug(f'get_platform_id: type:{type(platform_id)} \n{platform_id}')
            if isinstance(platform_id,dict):
                result = None
            elif isinstance(platform_id,int):
                result = Platform.objects.get(pk=int(platform_id))
            else:
                result = Platform.objects.get(name__icontains=platform_id) 
        else:
            if required:
                raise serializers.ValidationError({'platform_id': '需要region ID'})
            else:
                result = None
        return result

class MultipleDeleteSerializer(serializers.Serializer):
    ids = serializers.ListField(required=True, write_only=True)
    @action(methods=['delete'], detail=False) 
    def multiple_delete(self, request, *args, **kwargs):
         # 获取要删除的对象们的主键值
        delete_ids = request.data.get('ids')
        if not delete_ids:
            return Response(data={'detail': '参数错误,ids为必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not isinstance(delete_ids, list):
            return Response(data={'detail': 'ids格式错误,必须为List'}, status=status.HTTP_400_BAD_REQUEST)
        queryset = self.get_queryset()
        del_queryset = queryset.filter(id__in=delete_ids)
        if len(delete_ids) != del_queryset.count():
            return Response(data={'detail': '删除数据不存在'}, status=status.HTTP_400_BAD_REQUEST)
        del_queryset.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)